// Ad-hoc object (singleton) to handle asynch http requests
async_h = new Object();
async_h.IsBusy = false;
async_h.LoadData = LoadData;
async_h.CallBack;

function LoadData (url, callback){
   if (this.IsBusy){
      return "ASYNC_H_ERR_BUSY";
   }
   else {
      this.IsBusy = true;
   }
   this.CallBack = callback;
   if (url != null)
   {
      try {
         var f = document.getElementById('async_loader');
         f.src = url;
      }
      catch (err){
         alert(err);
         this.IsBusy = false;
         return "ASYNC_H_ERR_LOADING";
      }
   }
   this.IsBusy = false;
}

function NotifySink () {
   // Call back using the async_h provided function
   async_h.CallBack(window.async_loader.data);
}

function load_selector(url){
   async_h.LoadData(url, mainSelector_callback);
}

function mainSelector_callback(data){
   var elem_id ="country";
   load_options(elem_id, data);
   load_selector_sub();
}

function subSelector_callback(data){
   var elem_id = "town";
   load_options(elem_id, data);
}

function load_selector_sub(){
   var select = document.getElementById("country");
   var selection = select.selectedIndex;

/* MOVING THE CODE TO A SPECIFIC FUNCTION */
   clear_options("town");
   async_h.LoadData(select.options[select.selectedIndex].text.toLowerCase() + ".html", subSelector_callback);
}


function clear_options(elem_id) {
   try {
      var x=document.getElementById(elem_id);
      var l=x.options.length;
      for (i=0;i<l;i++){
         x.remove(0);
      }
   }
   catch (err){
      alert(err);
   }
}

function load_options(elem, option_array){
   var x=document.getElementById(elem);

   for (i=0; i< option_array.length;i++){
      var y=document.createElement('option');
      y.text=option_array[i];
      x.add(y, null);
   }
}

